use std::fs;
use std::io::*;
use std::net::{TcpListener, TcpStream};
fn handle_client(mut stream: TcpStream) {
    let mut buffer = [0; 512];
    stream.read(&mut buffer).unwrap();
    println!("收到了{}", String::from_utf8_lossy(&buffer[..]));

    let get = b"GET / HTTP/1.1\r\n";

    // if buffer.starts_with(get) {
    //     let content = fs::read_to_string("main.html").unwrap();
    //     // let reponse="HTTP/1.1 200 OK \r\n\r\n";
    //     let reponse = format!("HTTP/1.1 200 OK \r\n\r\n{}", content);
    //     stream.write(reponse.as_bytes());
    //     stream.flush().unwrap();
    // } else {
    //     let content = fs::read_to_string("404.html").unwrap();
    //     let reponse = format!("HTTP/1.1 404 not find \r\n\r\n{}", content);
    //     stream.write(reponse.as_bytes());
    //     stream.flush().unwrap();
    // }
    let (status_line, filename) = if buffer.starts_with(get) {
        ("HTTP/1.1 200 OK \r\n\r\n", "main.html")
    } else {
        ("HTTP/1.1 404 NOT FIND \r\n\r\n", "404.html")
    };
    let content = fs::read_to_string(filename).unwrap();
    let reponse = format!("{}{}", status_line, content);
    stream.write(reponse.as_bytes());
    stream.flush().unwrap();
}

fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:9090")?;

    for stream in listener.incoming() {
        handle_client(stream?);
    }
    Ok(())
}
